import { Component, Inject } from '@angular/core';
import { PersonnelService } from '../../services/personnel.service';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

export interface DialogData {
  status: number;
}
@Component({
  selector: 'm-synchronize',
  templateUrl: './synchronize.component.html',
  styleUrls: ['./synchronize.component.scss'],
})
export class SynchronizeComponent {
  constructor(
    public personnelService: PersonnelService,
    public dialogRef: MatDialogRef<SynchronizeComponent>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData,
  ) { }
  interval: any;
  status: number = this.data.status || -1;
  errMessage: string = ''
  ngOnInit() { }
  startSynchronize() {
    //开始同步
    this.status = 0;
    this.personnelService.synchronize().then((res) => {
      this.syncStasus();
    }).catch((e) => {

      if (('' + e.error).length > 2) {
        this.errMessage = e.error
      }
      console.log('map ee----------:', e)
      setTimeout(() => {
        (document.querySelector('.toast.toast-error')).remove()
      })
    })

  }
  //关闭弹窗
  close() {
    this.dialogRef.close();
    setTimeout(() => {
      this.errMessage = ''
    }, 200)

    if (this.status == 1) {
      location.reload()
    }

  }
  //定时器查询是否完成同步
  syncStasus() {
    clearInterval(this.interval);
    this.interval = setInterval(() => {
      /**
       * 0 同步中
       * 1 同步成功 清楚定时器
       * 2 同步失败 清除定时器
       * */
      this.personnelService.syncStatus().subscribe((res: any) => {
        if (res.code === 0 && (res.message === 1 || res.message === 2)) {
          clearInterval(this.interval);
        }

        this.status = res.message;
        console.log('this.status---:', this.status)
      },
        err => {
          this.status = 2
        }
      )

    }, 5000);
  }
}
